package com.rq.base.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.Toast;

import com.rq.base.BASE;


public class ToastUtil {
  /**
   * 避免Toast重复显示之前显示的内容
   */
  private static String oldMsg;
  private static Toast toast = null;
  private static long oneTime = 0;
  private static long twoTime = 0;

  public static void show(String text) {
    show(BASE.getCxt(), text);
  }

  public static void show(int resId) {
    show(BASE.getCxt(), BASE.getCxt().getString(resId));
  }

  public static void show(final Context context, final String content) {
    showToastAvoidRepeated(context, content);
  }

  public static void show(final Context context, final int content) {
    showToastAvoidRepeated(context, context.getString(content));
  }

  private static Handler mainHandler = new Handler(Looper.getMainLooper());

  private static void showToastAvoidRepeated(Context context, String message) {
    LOG.e("ToastUtil", "showToastAvoidRepeated.42:" + message);
    Context ctx = context == null ? BASE.getCxt() : context;
    if (TextUtils.isEmpty(message)) {
      return;
    }
    if (toast == null) {
      showToast(ctx, message);
      oneTime = System.currentTimeMillis();
      LOG.e("ToastUtil", "showToastAvoidRepeated.49:" + message);
    } else {
      twoTime = System.currentTimeMillis();
      if (message.equals(oldMsg)) {
        if (twoTime - oneTime > Toast.LENGTH_SHORT) {
          showToast(ctx, message);
          LOG.e("ToastUtil", "showToastAvoidRepeated.55:" + message);
        } else {
          LOG.e("ToastUtil", "showToastAvoidRepeated.54:" + message);
        }
      } else {
        LOG.e("ToastUtil", "showToastAvoidRepeated.60:" + message);
        oldMsg = message;
        showToast(ctx, message);
      }
    }
    oneTime = twoTime;
  }

  private static void showToast(final Context ctx, final String message) {
    if (Looper.myLooper() == Looper.getMainLooper()) {//主线程
      try {
        toast = Toast.makeText(ctx, null, Toast.LENGTH_SHORT);
        toast.setText(message);  //先置null，在设值，解决小米带appName问题
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
      } catch (Exception e) {

      } finally {
        toast = null;
      }
    } else {
      mainHandler.post(new Runnable() {
        @Override
        public void run() {
          toast = Toast.makeText(ctx, null, Toast.LENGTH_SHORT);
          toast.setText(message);  //先置null，在设值，解决小米带appName问题
          toast.setGravity(Gravity.CENTER, 0, 0);
          toast.show();
          toast = null;
        }
      });
    }
  }

  public static void cancelToast() {
    if (toast != null) {
      toast.cancel();
      toast = null;
    }
  }
}
